package com.andrew.dao.impl;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.print.attribute.ResolutionSyntax;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.andrew.dao.CustomerDao;
import com.andrew.dao.OrderDao;
import com.andrew.entity.Book;
import com.andrew.entity.Customer;
import com.andrew.entity.Order;
import com.andrew.entity.OrderBeanForAdmin;
import com.andrew.entity.OrderDetail;
import com.andrew.entity.OrderDetailBean;
import com.andrew.entity.OrderDetailForAdmin;
import com.andrew.util.JDBCUtils;
import com.sun.org.apache.bcel.internal.generic.NEW;


public class OrderDaoImpl implements OrderDao {
	private QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
	private CustomerDao customerDao=new CustomerDaoImpl();
	/**
	 * 添加订单
	 */
	@Override
	public void addOrder(Order order,Connection conn) throws SQLException {
		String sql="insert into orders values(?,?,?,?,?,?,?)";
		//转换为sql的date
		//Timestamp time=new Timestamp(order.getCreateDate().getTime());
		String time=order.getCreateDate();
		//设置参数
		Object[] params= {order.getOrderId(),order.getAddress(),
				order.getCustomer().getCustomerId(),order.getTotalPrice(),time,order.getSTATUS(),order.getVC()};
		qr.update(conn,sql,params);
		
		
	}

	/**
	 * 添加订单详情
	 */
	@Override
	public void addOrderDetailList(List<OrderDetail> orderDetailsList,Connection conn) throws SQLException {
		// TODO Auto-generated method stub
		String sql="insert into OrderDetail values(?,?,?,?,?,?)";
		Object[][] params=new Object[orderDetailsList.size()][];
		
		//给参数赋值
		for(int i=0;i<orderDetailsList.size();i++) {
			OrderDetail orderDetail=orderDetailsList.get(i);
			params[i]=new Object[] {orderDetail.getOrderDetailId(),orderDetail.getOrder().getOrderId(),
					orderDetail.getSubTotal(),orderDetail.getBook().getBookId(),orderDetail.getQuantity(),orderDetail.getSTATUS()};
		}
		
		qr.batch(conn,sql, params);
	}
	/**
	 * 获取当前用户的订单详情
	 */
	@Override
	public List<Order> getOrderByCustomerId(Customer customer) throws SQLException {
		//查询当前用户的所有订单
		String sql="select * from orders where CustomerId=?";
		List<Order> orders= qr.query(sql, new BeanListHandler<Order>(Order.class),customer.getCustomerId());
		//获取每个订单的订单详情
		for(Order order:orders) {
			//为指定订单的添加订单详情
			loadOrderDetails(order);
			order.setCustomer(customer);
		}
		return orders;	
	}
	/**
	 * 获取全部订单
	 */
	@Override
	public List<Order> getAllOrders() throws SQLException {
		//查询当前用户的所有订单
		String sql="select * from orders";
		List<Order> orders= qr.query(sql, new BeanListHandler<Order>(Order.class));
		//获取每个订单的订单详情
		for(Order order:orders) {
			//为指定订单的添加订单详情
			loadOrderDetails(order);
			loadOrderCustomer(order);
		}
		return orders;	
	}
	/**
	 * 根据订单号获取单个订单信息
	 */
	@Override
	public Order getOrdersByOrderId(String orderId) throws SQLException {
		//查询当前订单
		String sql="select * from Orders where orderId=?";
		Order order=qr.query(sql,new BeanHandler<Order>(Order.class),orderId);
		//加载当前订单的订单详情
		loadOrderDetails(order);
		//加载当前订单的用户
		loadOrderCustomer(order);
		
		return order;
	}
	
	
	/**
	 * 加载订单用户
	 * @param order
	 * @throws SQLException
	 */
	private void loadOrderCustomer(Order order) throws SQLException {
		String sql="select CustomerId from Orders where OrderId=?";
		int customerId=qr.query(sql,new ScalarHandler<Integer>(),order.getOrderId());
		Customer customer=customerDao.findCustomer(customerId);
		order.setCustomer(customer);
	}

	/**
	 * 加载订单详情
	 * @param order
	 * @throws SQLException
	 */
	private void loadOrderDetails(Order order) throws SQLException {
		//查询出OrderDetail中的每一行数据封装在map集合中，再把全部数据封装在list中
		String sql="select * from OrderDetail o,Book b where o.BookId=b.BookId and OrderId=?";
		List<Map<String, Object>> orderDeatilsmapList = qr.query(sql, new MapListHandler(),order.getOrderId());
		//将查询出的mapList转化为orderDeatailList
		List<OrderDetail> orderDetails=toOrderDeatailList(orderDeatilsmapList);
		
		order.setOrderDetailsList(orderDetails);
	}

	
	private List<OrderDetail> toOrderDeatailList(List<Map<String, Object>> orderDeatilsmapList) {
		List<OrderDetail> orderDetailList=new ArrayList<OrderDetail>();
		//遍历每一行的数据
		for(Map<String, Object> map :orderDeatilsmapList) {
			//将每行数据封装到OrderDetail中
			OrderDetail od=toOrderDetail(map);
			//把转换完的数据封装到orderDetailList中
			orderDetailList.add(od);
		}
		
		return orderDetailList;
	}

	private OrderDetail toOrderDetail(Map<String, Object> map) {
		//获取订单详情
		Book book=new Book();
		OrderDetail od=new OrderDetail();
		//遍历添加
		Set<String> set=map.keySet();
		for(String key:set) {
			switch (key) {
			case "OrderDetailId": od.setOrderDetailId((int)map.get(key));break;
			case "STATUS":od.setSTATUS((int)map.get(key));break;
			case "subTotal": od.setSubTotal((BigDecimal)map.get(key));break;
			case "quantity": od.setQuantity((int)map.get(key));break;
			case "Author":book.setAuthor((String)map.get(key));break;
			case "BookId":book.setBookId((int)map.get(key));break;
			case "BookName":book.setBookName((String)map.get(key));break;
			case "Description":book.setDescription((String)map.get(key));break;
			case "Picture":book.setPicture((String)map.get(key));break;
			case "Price":book.setPrice((BigDecimal)map.get(key));break;
			case "Stock":book.setStock((int)map.get(key));break;
			default:
				break;
			}
		}
		
		od.setBook(book);
		return od;
	}

	
	/**
	 * 修改订单状态 
	 */
	@Override
	public int updateOrderStatus(String  orderId, int status) throws SQLException {
		return qr.update("UPDATE Orders set STATUS=? where OrderId=?",status,orderId);
		
	}

	/**
	 * 设置收货地址
	 */
	@Override
	public void setAddress(String orderId, String address) throws SQLException {
		String sql="update Orders set Address=? where OrderId=?";
		qr.update(sql,address,orderId);
	}

	/**
	 * 删除一个订单详情
	 * @throws SQLException 
	 */
	@Override
	public int deleteOrderDetail(String orderId, int bookId,Connection con) throws SQLException {

		String sql="delete from OrderDetail where OrderId=? and BookId=?";
		qr.update(con,sql,orderId,bookId);
		long orderDetailNum=qr.query(con,"select count(*) from OrderDetail where OrderId=?", new ScalarHandler<Long>(),orderId);
		return (int)orderDetailNum;
	}

	/**
	 * 更新订单总价
	 */
	@Override
	public int updateOrderPrice(String orderId,Connection con) throws SQLException {
		BigDecimal totalPrice=new BigDecimal(0);
		List<Object[]> query = qr.query(con,"select subTotal from OrderDetail where OrderId=?", new ArrayListHandler(),orderId);
		
		for(Object[] p:query) {
			BigDecimal subPrice=(BigDecimal)p[0];
			totalPrice=totalPrice.add(subPrice);
		}

		
		String sql="update orders set totalPrice=? where OrderId=?";
		return qr.update(con,sql,totalPrice,orderId);
	}

	/**
	 * 删除订单
	 */
	@Override
	public int deleteOrderByOrderId(String OrderId,Connection con) throws SQLException {
		return qr.update(con,"delete from orders where OrderId=?",OrderId);
	}

	/**
	 * 更新订单详情的数量和小计
	 * @throws SQLException 
	 */
	@Override
	public void updateOrderDetailQuantityAndsubTotail(String orderId, int bookId, int newQuantity, Connection con) throws SQLException {
		Book book=new BookDaoImpl().queryBookbyBookId(bookId);
		BigDecimal price=new BigDecimal(newQuantity).multiply(book.getPrice());
		
		String sql="update OrderDetail set quantity=?,subTotal=? where orderId=? and bookId=?";
		qr.update(con,sql,newQuantity,price,orderId,bookId);
	}

	/**
	 * 评论完毕
	 */
	@Override
	public void updateOrderDetailStatus(int orderDetailID) throws SQLException {
		String sql="update OrderDetail set STATUS=? where OrderDetailId=?";
		qr.update(sql,1,orderDetailID);
	}

	@Override
	public OrderDetail getOrderDetailByOrderDetailId(int orderDetailId) throws SQLException {
		OrderDetailBean orderDetailBean = qr.query("select * from OrderDetail where OrderDetailId=?",new BeanHandler<OrderDetailBean>(OrderDetailBean.class),orderDetailId);
		OrderDetail orderDetail=new OrderDetail();
		orderDetail.setOrderDetailId(orderDetailBean.getOrderDetailId());
		orderDetail.setQuantity(orderDetailBean.getQuantity());
		orderDetail.setSTATUS(orderDetailBean.getSTATUS());
		orderDetail.setSubTotal(orderDetailBean.getSubTotal());
		
		Book book=new BookDaoImpl().queryBookbyBookId(orderDetailBean.getBookId());
		Order order=new OrderDaoImpl().getOrdersByOrderId(orderDetailBean.getOrderId());
		orderDetail.setBook(book);
		orderDetail.setOrder(order);
		return orderDetail;
	}





	



}
